﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Text.RegularExpressions;

namespace Dotway.WPF.Controls.Converters
{
    [ValueConversion(typeof(Color), typeof(string))]
    public class ColorToHexConverter: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Color color = (Color)value;            
            return color.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string hex = (string)value;            
            
            // Check hex string.
            Regex isHexDigit = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
            StringBuilder checkedHex = new StringBuilder();
            char[] hexChars = hex.ToCharArray();
            foreach (char c in hexChars)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                {
                    checkedHex.Append(c);
                }
            }
            hex = checkedHex.ToString();

            string r = string.Empty;
            string g = string.Empty;
            string b = string.Empty;
            string a = "FF";

            if (hex.Length == 6)
            {
                r = hex.Substring(0, 2);
                g = hex.Substring(2, 2);
                b = hex.Substring(4, 2);                
            }
            else if (hex.Length == 8)
            {
                a = hex.Substring(0, 2);
                r = hex.Substring(2, 2);
                g = hex.Substring(4, 2);
                b = hex.Substring(6, 2); 
            }
            
            Color color = Color.FromArgb(255, 0, 0, 0);
            try
            {
                int ai = Int32.Parse(a, System.Globalization.NumberStyles.HexNumber);
                int ri = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber);
                int gi = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber);
                int bi = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber);
                color = Color.FromArgb((byte)ai, (byte)ri, (byte)gi, (byte)bi);
            }
            catch
            { }

            return color;
        }

        #endregion
    }
}
